import binascii
import logging
import time
import serial

class JDQSerialController:
    def __init__(self, port='COM4', baudrate=9600, timeout=1):
        """
        初始化 继电器开关 串口控制器。

        :param port: 串口号,例如 'COM3' 或 '/dev/ttyUSB0'
        :param baudrate: 波特率,默认为 9600
        :param timeout: 超时时间,默认为 1 秒
        """
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.ser = serial.Serial(self.port, self.baudrate, timeout=self.timeout)

    @staticmethod
    def str_to_hex_bytes(hex_string):
        """
        转换字符串为数组,并添加 CRC 校验。

        :param hex_string: 输入的十六进制字符串
        :return: 包含 CRC 校验的字节数组
        """
        hex_string = str(hex_string).replace(' ', '').replace('[', '').replace(']', '').replace('\'', '')

        if ((len(hex_string) % 2) != 0):
            hex_string += " "

        c_16_temp = list(hex_string)
        ilen = int(len(c_16_temp) / 2)
        hexBytes = [0] * ilen
        for index in range(ilen):
            hexBytes[index] = int((c_16_temp[2 * index] + c_16_temp[2 * index + 1]),16)
        return hexBytes
    
    def send_command(self, command):
        """
        向 IT6720 发送命令。

        :param command: 要发送的命令,可以是字符串或 16 进制字节数组
        :return: 设备返回的响应
        """

        # 判断传入变量类型
        if isinstance(command, str):
            req = self.str_to_hex_bytes(command)
        else:
            req = command

        reqstr = binascii.b2a_hex(bytearray(req), ' ')
        print("reqstr: " + str(reqstr))
        self.ser.write(req)
        # 读取设备的响应
        response = self.ser.readline()
        resqstr = binascii.b2a_hex(bytearray(response), ' ')
        print("response: " + str(resqstr))

        return response
    
    def SetPort(self, Port, OnOff = 0):
        """
        设置继电器开关的状态。
        """
        bPort = self.select_switch_road(Port, OnOff)
        response = self.send_command('AA 5A 00 {:02X} 00 FF'.format(bPort))
        
    
    def select_switch_road(self, i, i_type):
        b_port = 0xFF
        if i == 1:
            b_port = 0x01 if i_type == 1 else 0x00
        elif i == 2:
            b_port = 0x11 if i_type == 1 else 0x10
        elif i == 3:
            b_port = 0x21 if i_type == 1 else 0x20
        elif i == 4:
            b_port = 0x31 if i_type == 1 else 0x30
        elif i == 5:
            b_port = 0x41 if i_type == 1 else 0x40
        elif i == 6:
            b_port = 0x51 if i_type == 1 else 0x50
        elif i == 7:
            b_port = 0x61 if i_type == 1 else 0x60
        elif i == 8:
            b_port = 0x71 if i_type == 1 else 0x70
        elif i == 9:
            b_port = 0x81 if i_type == 1 else 0x80
        elif i == 10:
            b_port = 0x91 if i_type == 1 else 0x90
        elif i == 11:
            b_port = 0xA1 if i_type == 1 else 0xA0
        elif i == 12:
            b_port = 0xB1 if i_type == 1 else 0xB0
        elif i == 18:
            b_port = 0xFF if i_type == 1 else 0xFE
        elif i == 19:
            b_port = 0xFC
        return b_port
    
    def close(self):
        """
        关闭串口。
        """
        self.ser.close()

    

# 示例：创建 IT6720SerialController 实例并使用
if __name__ == "__main__":

        # 请替换为实际的串口号
        serial_port = 'COM4'
        # 创建 IT6720SerialController 实例
        controller = JDQSerialController(serial_port)
        controller.SetPort(6, 0)